Ext.define('BookmarkIt.view.bookmarkView' ,{
    extend: 'Ext.view.View',
    alias: 'widget.bookmarkView',
    //store: 'BookmarkIt.store.localBookmarks',
    id:'bookmarkView',
    width:'100%',
    autoScroll:true,
    height:'100%',
    tpl: [
         '<tpl for=".">',
              '<tpl if="url==\'\'">',
                   '<div class="thumb-wrap folder" id="{id}">',
                   '<div class="thumb">',
                   		'<div id="{id}folder-bg" class="folder-bg" style="background-color:#{color}"></div>',
                   		'<img draggable="false" src="resources/images/folder128.png" />',
                   	'</div>',
                   '<span class="editable" style="font-weight:bold;font-family:cursive;">{title:htmlEncode}</span>',
                   '</div>',
              '<tpl else>',
                   '<div class="thumb-wrap" id="{id}" style="background:#{color} !important;">',    
                   '<tpl if="width &gt;= height">',
                   		'<div class="thumb"><img draggable="false" src="{icon}" title="{title:htmlEncode}" style="width:{width}px !important;height:{height}px !important;"/></div>',
                   '<tpl else >',
                   		'<div class="thumb"><img draggable="false" src="{icon}" title="{title:htmlEncode}" style="width:{width}px !important;height:{height}px !important;"/></div>',
                   '</tpl>',
                   '<a href="{url}" class="editable" style="font-weight:bold;font-family:cursive;">{title:htmlEncode}</a>',
                   '</tpl>',
                   '</div>',
               '</tpl>',
        '<div class="x-clear"></div>'
      ],
      multiSelect: true,
      trackOver: true,
      overItemCls: 'x-item-over',
      itemSelector: 'div.thumb-wrap',
      emptyText: 'No bookmarks to display', 
      listeners:{
          afterrender : function(){
        	  		this.bindStore(Ext.getStore('BookmarkIt.store.localBookmarks'));
              		this.controller = window.controller;
              		var bookmarkController = window.controller;
              		var store = bookmarkController.getStore('BookmarkIt.store.localBookmarks');
              		bookmarkController.v = this;
              		var v = this;
              		
					var sourceEl, image;
					
					this.dragZone = Ext.create('Ext.dd.DragZone',v.getEl(),
									{
										onStartDrag : function(x, y) {
											bookmarkController.dragStarted = true;
											var dragged = store.getById(parseInt(sourceEl.id,10));
											bookmarkController.dragged = dragged;
										},

										onMouseUp : function() {
											console.log('ONMOUSEUP');
											function swapId(a,b) {
												var dragged = store.getById(a);
												var itemOver = store.getById(b);
												var tempId = dragged.get('id');
												dragged.setId(itemOver.get('id'));
												itemOver.setId(tempId);	
												dragged.save();
												itemOver.save();
											}								

											if (bookmarkController.dragStarted) {
												if (bookmarkController.arr.length > 0) {
													var map = {};
													map[bookmarkController.arr[0][0]] = bookmarkController.arr[0][1];
													map[bookmarkController.arr[bookmarkController.arr.length - 1][0]] = bookmarkController.arr[bookmarkController.arr.length - 1][1];
													var key;
													var val;
													var i;
													for (i = 0; i + 1 < bookmarkController.arr.length; i++) {
														key = bookmarkController.arr[i][1];
														val = bookmarkController.arr[i + 1][1];
														map[key] = val;
													}
													var record;
													var folderId;
													if(store.snapshot){
														
													}

												}

												if (bookmarkController.dragged) {
													var y;
													for (y = bookmarkController.arr.length - 1; y > -1; y--) {
														swapId(bookmarkController.arr[y][0],bookmarkController.arr[y][1]);
													}
													store.load();
													bookmarkController.arr = [];
												}
											}
											bookmarkController.dragStarted = false;
										},
										getDragData : function(e) {
										
										if(bookmarkController.getStore('BookmarkIt.store.localBookmarks').sorters.length===0 && bookmarkController.searchMode===false){
											sourceEl = e.getTarget(v.itemSelector,10);
											if (sourceEl) {
												image = sourceEl.cloneNode(true);
												image.id = sourceEl.id
														+ 'image';
												image.style.width = '95px';
												v.dragData = {
													sourceEl : sourceEl,
													repairXY : Ext.fly(sourceEl).getXY(),
													ddel : image
												};
                                                return v.dragData;
											}
										}else {
											return null;
										}
										},
										getRepairXY : function() {
											var v = this;
											var sourceElement = Ext.get(sourceEl.id);
											sourceElement.fadeIn({duration : 700});
											sourceElement.setVisible(true);

											return v.dragData.repairXY;
										}, 
										afterDragEnter : function(target,e, id) {
											Ext.get(bookmarkController.dragged.get('id').toString()).fadeOut();
										}
									});

					this.dropZone = Ext.create(
									'Ext.dd.DropZone',
									v.getEl(),
									{

										dropNotAllowed : 'none',

										getTargetFromEvent : function(e) {
											return e.getTarget('.thumb-wrap');
										},

										onNodeEnter : function(target,dd, e,data) {
										},

										onNodeOut : function(target,dd, e,data) {
										    if(parseInt(target.id,10)===parseInt(bookmarkController.dragged.get('id'),10)){
										        bookmarkController.itemOver = null;
										    }
										},

										onNodeOver : function(target,dd, e,data) {
											if (sourceEl.id !== target.id
													&& bookmarkController.getStore('BookmarkIt.store.localBookmarks')
															.getById(parseInt(target.id,10)).get('url') !== '') {
												var dragged = store.getById(bookmarkController.dragged.get('id'));
												var itemOver = store.getById(parseInt(target.id,10));
												var itemOverIndex = store.indexOf(itemOver);
												var top = bookmarkController.arr[bookmarkController.arr.length - 1];

												bookmarkController.dragged = dragged;
												bookmarkController.itemOver = itemOver;

												/*if (store.indexOf(dragged) === itemOverIndex - 1|| store.indexOf(dragged) === itemOverIndex + 1) {
													store.remove(dragged);
													store.insert(itemOverIndex,dragged);
													v.dragData.repairXY = Ext.fly(Ext.get(dragged.get('id').toString())).getXY();
												} else{
													v.dragData.repairXY = Ext.fly(Ext.get(itemOver.get('id').toString())).getXY();
												}*/
												
												if (store.indexOf(dragged) !== itemOverIndex - 1|| store.indexOf(dragged) !== itemOverIndex + 1) {
													var i;
													if(store.indexOf(dragged)>itemOverIndex){
														for(i=store.indexOf(dragged)-1;i>itemOverIndex;i--){
															bookmarkController.arr.push([dragged.get('id'),store.getAt(i).get('id')]);
														}
													}else{
														for(i=store.indexOf(dragged)+1;i<itemOverIndex;i++){
															bookmarkController.arr.push([dragged.get('id'),store.getAt(i).get('id')]);
														}
													}
                                                }
												
												if (!top|| top[1] !== itemOver.get('id')) {
													console.log('add to arr');
													bookmarkController.arr.push([dragged.get('id'),itemOver.get('id') ]);
												} 
												else if (store.indexOf(dragged) === itemOverIndex - 1
														|| store.indexOf(dragged) === itemOverIndex + 1 || store.indexOf(dragged)===itemOverIndex){
													console.log('destroy');
													bookmarkController.arr.length = bookmarkController.arr.length - 1;
												}
															
												store.remove(dragged);
                                                store.insert(itemOverIndex,dragged);
                                                v.dragData.repairXY = Ext.fly(Ext.get(dragged.get('id').toString())).getXY();
												Ext.get(dragged.get('id').toString()).setVisible(false);
											}
											return Ext.dd.DropZone.prototype.dropAllowed;
										},

										onNodeDrop : function(target,dd, e,data) {
											if (sourceEl.id !== target.id
													&& bookmarkController.getStore('BookmarkIt.store.localBookmarks').getById(parseInt(target.id,10))
															.get('url') === '') {
												var dragModel = store.getById(parseInt(sourceEl.id,10));
												dragModel.set('folderId',target.id);
												dragModel.save();
												store.load();
												//store.sync();
												store.filter({
															filterFn : function(rec) {
																return parseInt(rec.get("folderId"),10) === bookmarkController.getCurrentFolderId();
															}
														});

												return true;
											}
											return false;
										}
									});
          },
          itemclick : function(obj, rec, item,index, event) {
              this.focus();
          },
          itemdblclick : function(obj, rec, item,index, event) {
				if (rec.get('url') === '') {
					this.controller.folderExplore(obj,rec, item,index, event);
				}
          },
          itemkeydown : function(obj, rec, item,index, event) {
				if (event.getKey() === event.DELETE) {
					this.controller.onBookmarkDelClick();
				}
          },
          itemcontextmenu: function(obj,record,item,index,event){
        	  event.preventDefault();
    	  
        	  var containsFolder = new RegExp('folder');
        	  
        	  var store = Ext.getStore('BookmarkIt.store.localBookmarks');
        	  if(Ext.getCmp('colorPicker')){
        		  Ext.getCmp('colorPickerPanel').close();
        	  }
        	  Ext.create('Ext.window.Window',{
        		 id:'colorPickerPanel', 
        		 title:'Choose color',
        		 autoShow:true,
        		 layout:'fit',
        		 items:[{
        			 xtype:'colorpicker',
        			 id:'colorPicker',
        			 autoShow:true,
        			 listeners:{
        				 select:function(picker,color){
        					 var model = store.getById(+item.id);
        					 model.set('color',color);
        		        	
        					 if(containsFolder.test(item.className)){
	        					 var element = Ext.get(item.id+'folder-bg');
	    						 element.setStyle('background-color','#'+color);
	    						 element.setStyle('background-image','none');
        		        	 }else{
        		        		 var element = Ext.get(item.id);
        		        		 element.setStyle('background-color','#'+color)
        		        	 }
    						 model.save();        						 
        				 }
        			 }
        		 }]
        	  });
          }
      }
});
